<template>

  <div class="tree-container" >
    <el-container style="height: 500px; border: 1px solid #ebeef5">
      <el-aside  style=" min-width:200px;background-color: rgb(238, 241, 246)" width=null>
        <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6" style="width: 100%;height: 100%">




          <div  class="el-tree-wrap" style="height: 100%">
            <el-tree
              ref="tree"
              style="height: 100%"
              accordion
              node-key="id"
              :default-expanded-keys="idArr"
              :expand-on-click-node="false"
              :load="loadNode"
              :props="defaultProps"
              class="vab-filter-tree"
              highlight-current
              lazy


              @node-click="handleNodeClick"

            >
            <span slot-scope="{ node,data}" class="vab-custom-tree-node">
              <span class="vab-tree-item">
                <i v-if="node.data.rank == 4" class="el-icon-s-custom"></i>
                {{ node.label }}



              </span>
              <span class="vab-tree-options">

                <a class="vab-tree-btn" title="添加床位"   @click="() => append(node,'', 0)">

                 <i class="el-icon-circle-plus-outline" v-if="node.level==2" > {{ data.unit}}#/{{ data.floor}}F (单元/楼层)</i>


                </a>
              </span>
            </span>
            </el-tree>
          </div>
        </el-col>

      </el-aside>

      <el-container>


        <el-main>
          <el-table
            style="height: 92%"
            ref="tableSort"

            :default-sort="{prop:'unit', order:'ascending'}"
            @sort-change="changeTableSort"
            :data="list"
            v-loading="listLoading">

            <el-table-column
              show-overflow-tooltip
              label="楼层"
              sortable="'custom'"
              prop="floor"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="单元"
              sortable="'custom'"
              prop="unit"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="房间"
              width="200px"
              sortable="'custom'"
              prop="roomCode"
            ></el-table-column>

            <el-table-column
              show-overflow-tooltip
              label="床位"
              width="200px"
              sortable="'custom'"
              prop="bedCode"
            ></el-table-column>
<!--            <el-table-column-->
<!--              show-overflow-tooltip-->
<!--              prop="dailyFee"-->
<!--              label="日费用"-->

<!--            ></el-table-column>-->
<!--            <el-table-column-->
<!--              show-overflow-tooltip-->
<!--              label="月费用"-->
<!--              prop="monthlyFee"-->
<!--            ></el-table-column>-->

<!--            <el-table-column-->
<!--              show-overflow-tooltip-->
<!--              label="购置费用"-->
<!--              prop="purchaseCost"-->
<!--            ></el-table-column>-->


            <el-table-column label="使用状态" prop="statusName">
              <template slot-scope="scope">
                <span ><el-tag type="success">{{scope.row.statusName}}</el-tag></span>
              </template>
            </el-table-column>
            <el-table-column label="禁用状态" prop="disabled">
              <template slot-scope="scope">

                <el-switch
                  v-model="scope.row.disabled"
                  class="demo"
                  active-color="#F04134"
                  active-text="禁用"
                  inactive-color="#11CED2"
                  inactive-text="启用"
                  @change="switchChange(scope.$index, scope.row)"

                />

              </template>


            </el-table-column>
<!--            <el-table-column label="禁用状态" prop="disabled">-->
<!--              <template slot-scope="scope">-->
<!--                <togglesswitch-->
<!--                  v-model="scope.row.disabled"-->
<!--                  :value.sync="scope.row.disabled"-->
<!--                  @change="switchChange(scope.$index, scope.row)"-->

<!--                >-->
<!--                </togglesswitch>-->
<!--              </template>-->


<!--            </el-table-column>-->

            <el-table-column
              show-overflow-tooltip
              label="操作"
              width="180px"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button type="text"    @click="append(scope.$index, scope.row)">修改 <i class="el-icon-edit"></i></el-button>
                <el-button type="text"    @click="handleInfo(scope.$index, scope.row)">详情<i class="el-icon-tickets"></i></el-button>
                <el-button type="text" @click="handleDelete(scope.$index, scope.row)">
                  删除<i class="el-icon-delete"></i>
                </el-button>

              </template>
            </el-table-column>

          </el-table>
          <el-pagination
            :background="background"
            :total="total"
            :page-size="queryForm.limit"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          ></el-pagination>

        </el-main>

      </el-container>
    </el-container>



    <el-dialog
      :title="dialogTitle"
      :visible.sync="treeDialogVisible"
      class="tree-operate-dialog"
         width="400px"
      @close="treeDialogVisible = false"
      destroy-on-close
    >

      <el-form ref="treeForm" :model="treeForm"  :rules="rules" >
        <div class="active">
        <el-form-item label="机构名称" required >
<!--          <el-input v-model="treeForm.institutionName" :v-if=!isdisabled ></el-input>-->
          <span>
             {{treeForm.institutionName}}
          </span>
        </el-form-item>

        <el-form-item label="楼/房间信息" required>
<!--          <el-input v-model="treeForm.number" autocomplete="off"   v-if="!isdisabled" ></el-input>-->


 <span> {{treeForm.number}}#{{treeForm.unit}}#{{treeForm.floor}}F{{treeForm.roomCode}}(楼/单元/楼层/房间)</span>
        </el-form-item>
<!--        <el-form-item label="所属楼宇单元" required>-->
<!--&lt;!&ndash;          <el-input v-model="treeForm.unit" ></el-input>&ndash;&gt;-->
<!--&lt;!&ndash;          <span >&ndash;&gt;-->
<!--&lt;!&ndash;             {{treeForm.unit}}&ndash;&gt;-->
<!--&lt;!&ndash;          </span>&ndash;&gt;-->
<!--        </el-form-item>-->
<!--        <el-form-item label="所属房间编号" required>-->
<!--&lt;!&ndash;          <el-input v-model="treeForm.roomCode" v-if="!isdisabled"></el-input>&ndash;&gt;-->
<!--&lt;!&ndash;          <span>&ndash;&gt;-->
<!--&lt;!&ndash;             {{treeForm.roomCode}}&ndash;&gt;-->
<!--&lt;!&ndash;          </span>&ndash;&gt;-->
<!--        </el-form-item>-->
<!--        <el-form-item label="床位所在楼层数" required>-->
<!--&lt;!&ndash;          <el-input v-model="treeForm.floor" v-if="!isdisabled"></el-input>&ndash;&gt;-->
<!--          <span>-->
<!--             {{treeForm.floor}}楼-->
<!--          </span>-->

<!--        </el-form-item>-->
        </div>
        <el-form-item label="床位编号" prop="bedCode">
          <el-input v-model="treeForm.bedCode" v-if="!isdisabled" @input="change($event)"></el-input>
          <span v-if="isdisabled">
             {{treeForm.bedCode}}
          </span>

        </el-form-item>

<!--        <el-form-item label="日费用"  prop="dailyFee">-->
<!--          <el-input v-model="treeForm.dailyFee" type="number" min="0"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="月费用" prop="monthlyFee">-->
<!--          <el-input v-model="treeForm.monthlyFee" type="number"  min="0"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="购置费用" >-->
<!--          <el-input v-model="treeForm.purchaseCost"  type="number"  min="0"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="备注信息" >
          <el-input type="textarea" v-model="treeForm.remark"  style="width:100%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="treeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTree">确 定</el-button>
      </div>
    </el-dialog>
    <Info ref="info" ></Info>
  </div>
</template>

<script>

    import { findstoe } from "@/api/berth";
    import { findroom } from "@/api/berth";
    import { add } from "@/api/berth";
    import { search } from "@/api/berth";
    import { doDelete ,disable,enablebed} from "@/api/berth";
    import Info  from "./components/info";
    export default {
        name: "Berth",
        components: {Info},
        data() {
            return {
                dialogTitle: "添加节点",
                treeFlag: 0,
                listLoading: true,
                list: [],
                idArr:[],
                id: 0,
              institutionNumber:"",
                isdisabled:false,
                methodsType:'put',
                treeDialogVisible: false,
                treeForm: {
                    bedCode: "",
                    dailyFee: 0,
                    floor: "",
                    institutionNumber: "",
                    monthlyFee: 0,
                    number: "",
                    purchaseCost: 0,
                    remark: "",
                    roomCode: "",
                    unit: "",
                },
                total: 0,
                background: true,
                defaultProps: {
                    children: "children",
                    label: "name",
                    isLeaf: 'leaf',
                    flool:'1'

                },
                rules: {
                    bedCode: [
                        {required: true, message: '床位编号', trigger: 'blur'},

                    ],
                    dailyFee: [
                        {required: true, message: '日费用', trigger: 'blur'},

                    ],
                    monthlyFee: [
                        {required: true, message: '月费用', trigger: 'blur'},

                    ],
                    // purchaseCost: [
                    //     {required: true, message: '购置费用', trigger: 'blur'},
                    //
                    // ],
                },
                queryForm: {
                    currPageNo: 1,
                    limit: 12,
                    institutionNumber: "",
                    number: "",
                    roomCode: "",


                },
                room: {
                    institutionNumber: "",
                    number: ""
                },

            };
        },
      created: function () {
        this.$nextTick(function () {

          setTimeout(() => {
             console.log(localStorage.getItem("institutionNumber"))
            this.room.institutionNumber=localStorage.getItem("institutionNumber")
            this.institutionNumber=localStorage.getItem("institutionNumber")

          }, 1000);
        })
        this.search()
      },


        methods: {
            change(){
                this.$forceUpdate()
            },
            changeTableSort(column){

                var fieldName = column.prop;
                var sortingType = column.order;

                //按照降序排序
                if(sortingType == "descending"){
                    this.list = this.list.sort((a, b) => b[fieldName] - a[fieldName]);
                }
                //按照升序排序
                else{
                    this.list = this.list.sort((a, b) => a[fieldName] - b[fieldName]);
                }


            },

            // 添加节点操作
            append(node, data, flag) {
                this.treeFlag = flag;


                if (flag == 0) {
                    this.treeForm.bedCode=""
                    this.treeForm.dailyFee=0
                    this.treeForm.monthlyFee=0
                    this.methodsType = 'post'
                    this.dialogTitle = "添加床位";
                    this.isdisabled = false
                    this.treeForm=node.data
                    this.treeForm.remark=""
                    console.log(this.treeForm)
                } else {
                    this.methodsType = 'put'
                    this.dialogTitle = "编辑床位";
                    this.isdisabled = true
                    this.treeForm = {
                        ...data
                    }
                }

                this.treeDialogVisible = true;

            },

            switchChange(index,row){

              let number   =(row.number )
              let institutionNumber   =(row.institutionNumber )
              let roomCode    =(row.roomCode  )
              let floor    =(row.floor  )
              let unit    =(row.unit  )
              let bedCode     =(row.bedCode   )
                if(row.disabled==true){
                  disable({number,institutionNumber,roomCode,floor,unit,bedCode}).then(res => {


                    this.$baseMessage("已禁用",'success');


                  })
                }else {
                  enablebed({number,institutionNumber,roomCode,floor,unit,bedCode}).then(res => {


                    this.$baseMessage("已启用",'success');


                  })

                }
                setTimeout(() => {
                    this.listLoading = false;
                }, 500);

            },
            // 保存添加和编辑
            saveTree() {
                this.$refs.treeForm.validate(async (valid) => {
                    if (valid) {
                        console.log(this.id)
                        if(this.treeFlag!=undefined){
                            this.treeForm.dailyFee=0
                            this.treeForm.monthlyFee=0
                            this.treeForm.purchaseCost=0
                              this.methodsType='post'
                            const {code,data} = await add(this.treeForm,this.methodsType);
                          if(code==200){
                            this.$message({
                                message: "添加成功",
                                type: 'success'
                              }

                            );
                              this.treeDialogVisible=false
                            this.search();

                          }else {
                            return false
                          }

                        }else{
                          this.methodsType='put'
                            const {code,data} = await add(this.treeForm,this.methodsType);
                          if(code==200){
                            this.$message({

                                message: "修改成功",
                                type: 'success'
                              }

                            );
                              this.treeDialogVisible=false
                            this.search();

                          }else {
                            return false
                          }
                        }

                    }
                });
            },
            async loadNode(node, resolve) {
                if (node.level === 0) {

                    console.log(node)
                  setTimeout(() => {
                    let institutionNumber=localStorage.getItem("institutionNumber")

                    findstoe({institutionNumber}).then(res => {
                        let  id=0

                        console.log(res.data[id].id)
                        if(res.data){

                            this.idArr.push(res.data[id].id)

                        }else {

                        }

                       resolve(res.data);

                    })
                  }, 1000);






                } else if (node.level === 1) {
                 console.log(node.data.name)
                    this.room.limit=999999
                    this.room.currPageNo=1
                    this.room.institutionNumber = node.data.institutionNumber
                    this.room.number = node.data.number
                     this.room.name =node.data.name
                    const {data} = await findroom(this.room);


                  let  list=[]
                    for (var i = 0; i < data.data.length; i++) {
                      data.data[i].leaf =true


                      list.push({
                        ...data.data[i],
                        name: data.data[i].roomCode,


                      })




                   }

                   resolve(list);
                  //  resolve(data.data)


                } else {
                    return false
                }
            },
            search() {

              this.queryForm.institutionNumber=localStorage.getItem("institutionNumber")
                this.listLoading = true;
                search(this.queryForm).then(res => {

                    this.list = res.data.data
                    this.total=res.data.total



                })
                setTimeout(() => {
                    this.listLoading = false;
                }, 500);
            },
            handleSizeChange(val) {
                this.queryForm.limit = val;
                this.search();
            },
            handleCurrentChange(val) {
                this.queryForm.currPageNo = val;
                this.search();
            },
            //点击树形组件事件
            handleNodeClick(data) {
                console.log(data);
                if (data.leaf == true) {
                    this.queryForm.number = data.number
                  this.queryForm.floor = data.floor
                  this.queryForm.unit = data.unit
                    this.queryForm.currPageNo = 1
                    this.queryForm.roomCode = data.roomCode
                    this.queryForm.institutionNumber = data.institutionNumber


                    this.search()

                } else {

                }

            },
            handleInfo(index,row) {

                this.$refs["info"].showEdit(row);
            },
            handleDelete(index, row) {
                let number = (row.number)
                let institutionNumber = (row.institutionNumber)
                let roomCode = row.roomCode
                let floor = row.floor
                let unit = row.unit
                let bedCode = row.bedCode
                if (row.id) {
                    this.$baseConfirm("你确定要删除当前项吗", null, async () => {
                        const {code, msg} = await doDelete(({
                            number,
                            institutionNumber,
                            roomCode,
                            floor,
                            unit,
                            bedCode
                        }));
                        if (code == 200) {

                            this.$baseMessage(msg, "success");
                            this.search();
                        } else {

                        }
                    });
                }
            },
        }

    }

</script>

<style scoped>
  .tree-container{
    height: calc( 100vh - 60px - 55px - 20px - 20px - 55px - 30px ) !important;
  }
  .tree-container >>> .el-container{
     height: 100% !important;
  }
  .tree-container >>>.el-tree-node__content{
    height:50px !important;
  }
.el-container>>>.el-icon-loading{
  display: none !important;
}
/*.active >>> .el-form-item--small{*/
/*   display: inline-block;*/
/*  width: 50%;*/
/*}*/
  .tree-container >>> .demo .el-switch__label {
    position: absolute !important;
    display: none !important;
    color: #fff !important;
  }
  .tree-container >>>.el-switch__core{
    width: 50px !important;
  }
  /*打开时文字位置设置*/
  .tree-container >>> .demo .el-switch__label--right {
    z-index: 1 !important;

  }
  /*关闭时文字位置设置*/
  .tree-container >>> .demo .el-switch__label--left {
    z-index: 1 !important;
    left: 19px !important;
    margin-right: 0px !important;
  }
  .tree-container  >>> .demo .el-switch__label.is-active span{
    font-size: 12px !important;
  }
  /*table-room*/
  .tree-container >>> .demo .el-switch__label.is-active {
    display: block !important;
  }
  .tree-container >>> .demo.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 50px !important !important;
  }

</style>
